import os
import datetime
import random
import uuid
import hashlib
from django.conf import settings
from web import models

# ''' md5加密,加盐 '''
def myMd5(str):
    # 加盐
    obj = hashlib.md5(bytes(settings.SECRET_KEY,'utf-8'))
    obj.update(str.encode('utf-8'))
    return obj.hexdigest()
# ''' 生成随机字符串 '''
def uid(string):
    data = "{}-{}".format(str(uuid.uuid4()), string)
    return myMd5(data)
"""生成订单编号"""
def getOrderNum():
    todaytime=datetime.datetime.now()
    # print(todaytime)
    # offset = datetime.timedelta(hours=8) #服务器时间少8小时
    # re_date = (todaytime + offset).strftime('%Y%m%d-%H%M%S')
    re_date = todaytime.strftime('%Y%m%d-%H%M%S')
    num=["0","1","2","3","4","5","6","7","8","9"]
    res=re_date+"-"+random.choice(num)+random.choice(num)+random.choice(num)+random.choice(num)
    return res
# """删除文件夹 返回要删除的文件夹对象列表"""
def deleteFolder(request,folder_object):
    del_folder_list = [folder_object,]
    childs = models.FileRepository.objects.filter(parent=folder_object,project=request.tracer.project).order_by('-file_type')
    for child in childs:
        print(child.name)
        # 遇到的是文件夹
        if child.file_type==2:
            del_folder_list.append(child)
            deleteFolder(request,child)
        # 遇到的是文件，则删除并归还空间
        delete_object = models.FileRepository.objects.filter(id=child.id, project=request.tracer.project).first()
        if delete_object.file_type == 1:
            file_dir = settings.FILES_DIR
            f = os.path.join(file_dir, delete_object.file_path)
            try:
                print("***************")
                os.remove(f)
                delete_object.delete()
            except Exception as e:
                print("-------------")
                print(e)
                delete_object.delete()
            # 删除文件，将容量还给当前项目的已使用空间
            request.tracer.project.used_size -= delete_object.file_size
            request.tracer.project.save()
    return del_folder_list

if __name__ == "__main__":
    print(getOrderNum())